package com.qianfeng.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianfeng.entity.dto.AdminModuleRole;
import com.qianfeng.entity.dto.AdminRole;
import com.qianfeng.mapper.AdminModuleRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class AdminModuleRoleService extends ServiceImpl<AdminModuleRoleMapper , AdminModuleRole> {

    @Autowired
    private AdminRoleService adminRoleService;

    @Transactional(readOnly = true)
    public List<AdminModuleRole> getByRoleId(Long roleId) {
        QueryWrapper<AdminModuleRole> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(AdminModuleRole::getAdminRoleId, roleId);
        return this.list(wrapper);
    }

    @Transactional
    public void saveRole(AdminRole role, String moduleRoles) {
        adminRoleService.saveOrUpdate(role);

        if(role.getId() != null){
            QueryWrapper<AdminModuleRole> deleteWrapper = new QueryWrapper<>();
            deleteWrapper.lambda().eq(AdminModuleRole::getAdminRoleId , role.getId());
            this.remove(deleteWrapper);
        }

        String[] amds = moduleRoles.split("\\|");
        List<AdminModuleRole> amdList = new ArrayList<>();

        for(String amd : amds){
            amdList.add(new AdminModuleRole(role.getId() , Long.parseLong(amd)));
        }
        this.saveBatch(amdList);
    }

    @Transactional
    public void removeByRoleId(Long roleId) {
        QueryWrapper<AdminModuleRole> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(AdminModuleRole::getAdminRoleId , roleId);
        this.remove(wrapper);
    }
}
